<template>
  <view class="baseForm">
    <view class="overhidden">
      <view
        v-show="!taskInfo?.id && loading === false"
        class="flex justify-center font-14"
        style="margin: 30px 0 30px 0"
        >暂无信息</view
      >
      <u-loading-icon
        class="flex justify-center mt-20"
        textSize="18"
        v-show="loading"
      ></u-loading-icon>
      <!-- 详情 -->
      <view class="detail card" v-if="taskInfo?.id && loading === false">
        <view class="flex flex-col justify-between flex-1 h-full">
          <view class="record-content">
            <view
              class="flex title justify-between"
              @click="() => (isCollapse = !isCollapse)"
              :class="!isCollapse ? 'u-m-b-24' : 'u-m-b-10'"
            >
              <text>基本信息</text>
              <u-icon
                v-show="!isCollapse"
                name="arrow-up"
                color="#000a7b"
              ></u-icon>
              <u-icon
                v-show="isCollapse"
                name="arrow-down"
                color="#000a7b"
              ></u-icon>
            </view>
            <view v-show="!isCollapse">
              <view class="record-item">
                <text>设备编号</text>
                <text>{{ taskInfo?.assetCode || "" }}</text>
              </view>
              <view class="record-item">
                <text>设备名称</text>
                <text>{{ taskInfo?.assetName || "" }}</text>
              </view>
              <view class="record-item" v-if="taskInfo?.planName">
                <text>维护任务</text>
                <text>{{ taskInfo?.planName || "" }}</text>
              </view>
              <view class="record-item" v-if="taskInfo?.locationName">
                <text>位置</text>
                <text>{{ taskInfo?.locationName || "" }}</text>
              </view>

              <view class="record-item" v-if="taskInfo?.executePersonName">
                <text>维护人</text>
                <text>
                  {{ taskInfo?.executePersonName || "" }}
                </text>
              </view>
              <view class="record-item" v-if="taskInfo?.workTime">
                <text>维护时间</text>
                <text>
                  {{ taskInfo?.workTime || "" }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="plan card record-content" v-if="taskInfo?.id">
        <view
          v-show="!taskInfo?.details || taskInfo?.details.length === 0"
          class="flex justify-start grey-color"
          style="margin: 12px 0 10px"
          >暂无点检信息</view
        >
        <view
          class="overhidden"
          v-for="(item, index) in taskInfo?.details"
          :key="index"
        >
          <view>
            <view class="record-content">
              <view class="record-item">
                <view class="title_new">
                  <text
                    class="require_icon"
                    v-if="item?.sopItem.sopExecute == '1'"
                    >*</text
                  >
                  {{ item?.sopItemName || "" }}
                  <u-icon
                    v-if="
                      item?.sopItem.sopItemMethod ||
                      item?.sopItem.sopItemStandardValue ||
                      item?.sopItem.sopItemTool ||
                      item?.sopItem.sopItemPosition
                    "
                    name="info-circle-fill"
                    color="rgb(192, 196, 204)"
                    size="18"
                    @click="openInfoModal(item.sopItem)"
                  ></u-icon>
                </view>
                <view
                  class=""
                  v-if="item.sopItem.standardValue == 1"
                  style="max-width: 100px; min-width: 70px"
                >
                  <u--input
                    v-if="props.isRead == 0"
                    v-model="item.sopItemValue"
                    placeholder="请输入"
                    class="minInput"
                    :class="
                      sizeColorHandle(
                        item.sopItemValue,
                        item?.sopItem.standardMinValue,
                        item?.sopItem.standardMaxValue
                      )
                    "
                    inputAlign="right"
                    clearable
                    border="none"
                  ></u--input>
                  <text
                    v-else
                    :class="
                      sizeColorHandle(
                        item.sopItemValue,
                        item?.sopItem.standardMinValue,
                        item?.sopItem.standardMaxValue
                      )
                    "
                    style="text-align: right"
                    class="text-span-flex-end"
                  >
                    {{ item.sopItemValue || "" }}
                  </text>
                </view>
                <view
                  class=""
                  v-if="item.sopItem.standardValue == 2"
                  style="max-width: 100px; min-width: 70px"
                >
                  <view
                    v-if="props.isRead == 0 || props.isRead == 5"
                    class="flex input-box"
                    style="justify-content: flex-end"
                  >
                    <view
                      class="minInput"
                      :class="
                        sizeColorHandle1(
                          item.sopItemValueId,
                          item.sopItem.details ?? []
                        )
                      "
                      @click.stop="
                        hideKeyboard(index, item.sopItem.details ?? [])
                      "
                    >
                      <view class="">
                        {{ item.sopItemValue ? item.sopItemValue : "" }}
                      </view>
                      <view class="" style="color: #c0c4cc">
                        {{ item.sopItemValue ? "" : "请选择" }}
                      </view>
                    </view>
                    <image
                      @click.stop="clearData(index)"
                      v-if="item.sopItemValueId !== ''"
                      src="@/static/image/delete.png"
                      class="deleteIcon"
                    />
                  </view>
                  <text
                    v-else
                    :class="
                      sizeColorHandle1(
                        item.sopItemValueId,
                        item.sopItem.details ?? []
                      )
                    "
                    style="text-align: right"
                    class="text-span-flex-end"
                  >
                    {{ item.sopItemValue || "" }}
                  </text>
                </view>
              </view>
              <!-- <view class="record-item" v-if="item.sopItem.standardValue == 1 && !(!item.sopItem.standardMinValue && !item.sopItem.standardMaxValue)">
										<text>上下限值</text>
										<text v-if="item?.sopItem.standardMinValue !== item?.sopItem.standardMaxValue">
											{{ item?.sopItem.standardMinValue || '' }}-{{ item?.sopItem.standardMaxValue || '' }}{{ item?.standardValueUnit || '' }}
										</text>
										<text v-else>{{ item?.sopItem.standardMinValue || '' }}{{ item?.sopItem.standardValueUnit || '' }}</text>
									</view> -->
              <view class="record-item" v-if="item.sopItemStandard">
                <text>标准要求</text>
                <text>{{ item.sopItemStandard }}</text>
              </view>
              <!-- <view
								class="record-item"
								v-if="item.sopItem.standardValue == 1">
								<view class="flex">
									实际值
									<text
										class="require_icon"
										v-if="item?.sopItem.sopExecute == '1'">
										*
									</text>
								</view>
								<u--input
									v-if="props.isRead == 0"
									v-model="item.sopItemValue"
									placeholder="请输入"
									class="minInput"
									:class="
										sizeColorHandle(
											item.sopItemValue,
											item?.sopItem.standardMinValue,
											item?.sopItem.standardMaxValue
										)
									"
									inputAlign="right"
									clearable
									border="none"></u--input>
								<text
									v-else
									:class="
										sizeColorHandle(
											item.sopItemValue,
											item?.sopItem.standardMinValue,
											item?.sopItem.standardMaxValue
										)
									">
									{{ item.sopItemValue || "" }}
								</text>
							</view>
							<view
								class="record-item"
								v-if="item.sopItem.standardValue == 2">
								<view class="flex">
									实际值
									<text
										class="require_icon"
										v-if="item?.sopItem.sopExecute == '1'">
										*
									</text>
								</view>
								<view
									v-if="props.isRead == 0"
									
									class="flex input-box">
									
									<view
										class="minInput"
										style="width:400rpx"
										:class="sizeColorHandle1(item.sopItemValueId, item.sopItem.details ?? [])"
										@click.stop="hideKeyboard(index, item.sopItem.details ?? [])"
										
									>
										<view class=""  >
											{{ item.sopItemValue? item.sopItemValue:'' }}
										</view>
										<view class="" style="color:#c0c4cc">
											{{ item.sopItemValue? '':'请选择' }}
										</view>
									</view>
									<image
										@click.stop="clearData(index)"
										v-show="item.sopItemValueId"
										src="@/static/image/delete.png"
										class="deleteIcon" />
								</view>
								<text
									v-else
									:class="
										sizeColorHandle1(
											item.sopItemValueId,
											item.sopItem.details ?? []
										)
									">
									{{ item.sopItemValue || "" }}
								</text>
							</view>
						 -->
            </view>
            <!-- 待需要上传图片后启用 -->
            <!-- <view class="mt-8 flex" v-if="item.sopItem.sopImage == '1'">
              <upload-image
                :multiple="false"
                :key="index"
                :keys="index"
                @fileChange="(list) => getImages(list, index)"
                :list="item.images ?? []"
                :capture="capture"
                :isRead="props.isRead == 1 ? true : false"
                folderName="eam/equ/routingInspection"
              ></upload-image>
            </view> -->
            <view class="mt-8 flex" v-if="item.sopItem.sopImage == '1'">
              维修前
            </view>
            <view class="mt-8 flex" v-if="item.sopItem.sopImage == '1'">
              <upload-image
                :multiple="false"
                :key="index * 20"
                :keys="index * 20"
                @fileChange="(list) => getBeforeImages(list, index)"
                :list="item.beforeImages ?? []"
                :capture="capture"
                :isRead="props.isRead == 1 ? true : false"
                folderName="eam/equ/selfMaintainPlan"
              ></upload-image>
            </view>
            <view class="mt-8 flex" v-if="item.sopItem.sopImage == '1'">
              维修后
            </view>
            <view class="mt-8 flex" v-if="item.sopItem.sopImage == '1'">
              <upload-image
                :multiple="false"
                :key="index"
                :keys="index"
                @fileChange="(list) => getImages(list, index)"
                :list="item.images ?? []"
                :capture="capture"
                :isRead="props.isRead == 1 ? true : false"
                folderName="eam/equ/selfMaintainPlan"
              ></upload-image>
            </view>
          </view>
          <u-divider
            v-show="index + 1 !== taskInfo?.details.length"
          ></u-divider>
        </view>
        <!-- 查看页面并且没有现场图片则不展示 -->
        <u-divider></u-divider>
        <view>
          <view class="title flex justify-between">
            <text class="mt-4">维护前图片</text>
          </view>

          <view class="mt-8">
            <view class="mt-8 flex">
              <upload-image
                :multiple="false"
                :keys="1212"
                @fileChange="getSceneImages1"
                :list="taskInfo.beforeImages ?? []"
                :capture="capture"
              ></upload-image>
            </view>
          </view>
        </view>
        <view>
          <view class="title flex justify-between">
            <text class="mt-4">维护后图片</text>
          </view>

          <view class="mt-8">
            <view class="mt-8 flex">
              <upload-image
                :multiple="false"
                :keys="4545"
                @fileChange="getSceneImages"
                :list="taskInfo.images ?? []"
                :capture="capture"
              ></upload-image>
            </view>
          </view>
        </view>
      </view>

      <!-- new 增加问题描述 problemDesc-->
      <view class="detail card" v-if="props.isRead == 0">
        <view class="flex flex-col justify-between flex-1 h-full">
          <view class="record-content">
            <view
              class="flex title justify-between"
              style="margin: 6px 0 !important"
            >
              <text>问题描述</text>
            </view>
          </view>
          <view class="record-item">
            <u--textarea
              v-model="taskInfo.problemDesc"
              placeholder="请输入"
              class="minTextarea"
              inputAlign="right"
              clearable
              border="none"
              maxlength="250"
              autoHeight
              height="auto"
            ></u--textarea>
          </view>
        </view>
      </view>
      <view
        class="detail card"
        v-if="props.isRead == 1 && taskInfo.problemDesc"
      >
        <view class="flex flex-col justify-between flex-1 h-full">
          <view class="record-content">
            <view
              class="flex title justify-between"
              style="margin: 6px 0 !important"
            >
              <text>问题描述</text>
            </view>
          </view>
          <view class="record-item">
            <view class="font-14" style="word-break: break-all">
              {{ taskInfo.problemDesc || "" }}
            </view>
          </view>
        </view>
      </view>

      <view
        style="margin-bottom: 70px"
        class="detail card"
        v-if="props.isRead == 0"
      >
        <view class="flex flex-col justify-between flex-1 h-full">
          <view class="record-content">
            <view
              class="flex title justify-between"
              style="margin: 6px 0 !important"
            >
              <text>备件更换</text>
            </view>
          </view>
          <view class="record-item">
            <view v-for="(item, index) in taskInfo.parts" :key="index">
              <!-- <view class="flex record-title">
													<text class="line1">{{ item.spareName }}</text>
												</view> -->
              <view
                class="flex flex-col justify-between flex-1 h-full record-content-body"
              >
                <view class="record-content">
                  <view class="record-item">
                    <!-- <text>
															{{ item.spareName }}
														</text>
														<text>
															{{ item.spareCode }}
														</text> -->
                    <view class="upload-scan-device" style="margin: 0px">
                      <view class="flex select-device-form">
                        <u-input
                          v-model="item.spareName"
                          shape="round"
                          bgColor="#fff"
                          :animation="true"
                          placeholder="请输入备件名称"
                          class=""
                          searchIcon=""
                          style="border: none"
                        ></u-input>
                      </view>
                      <u-button
                        style="width: 50px; min-width: 50px; margin-right: 2px"
                        size="small"
                        type="primary"
                        text="选择"
                        @click="selectPart(index)"
                      ></u-button>
                    </view>
                  </view>
                  <view class="record-item" style="align-items: center">
                    <view class="">
                      <u-number-box
                        :min="0"
                        buttonSize="26"
                        v-model="item.sparePartNumber"
                      ></u-number-box>
                    </view>
                    <u-icon
                      name="trash"
                      color="red"
                      size="20"
                      style="margin-right: -2px"
                      @click="handleDelete(index)"
                    ></u-icon>
                  </view>
                </view>
              </view>
              <u-divider style="margin: 0"></u-divider>
            </view>
            <u-button
              class="addBtn1"
              type="primary"
              text="新增"
              @click="addParts"
              style="
                height: 28px;
                width: 70px;
                text-align: center;
                justify-content: center;
                margin-left: 0;
                margin-top: 8px;
              "
            ></u-button>
            <!-- <u-button
											class="addBtn1"
											type="primary"
											text="新增"
											@click="jump('/eam/equ/selectParts/index')"
											style="
												height: 28px;
												width: 70px;
												text-align: center;
												justify-content: center;
												margin-left: 0;
												margin-top: 8px;
											"></u-button> -->
          </view>
        </view>
      </view>

      <view
        style="margin-bottom: 70px"
        class="detail card"
        v-if="props.isRead == 1 && taskInfo.parts"
      >
        <view class="flex flex-col justify-between flex-1 h-full">
          <view class="record-content">
            <view
              class="flex title justify-between"
              style="margin: 6px 0 !important"
            >
              <text>备件更换</text>
            </view>
          </view>
          <view class="record-item">
            <view v-for="(item, index) in taskInfo.parts" :key="index">
              <view
                class="flex flex-col justify-between flex-1 h-full record-content-body"
              >
                <view class="record-content">
                  <view class="record-item">
                    <text>{{ item.spareName }}</text>
                    <text>{{ item.spareCode }}</text>
                  </view>
                  <view class="record-item" style="align-items: center"
                    >数量：{{ item.sparePartNumber || 0 }}</view
                  >
                </view>
              </view>
              <u-divider
                v-show="index + 1 !== taskInfo?.parts.length"
                style="margin: 0"
              ></u-divider>
            </view>
          </view>
        </view>
      </view>

      <!-- 提交 -->
      <view v-if="props.isRead == 0" class="submit_btn_div">
        <button
          type="default"
          class="grey_btn"
          :disabled="saveLoading"
          :loading="saveLoading"
          @click="saveSubmit"
        >
          保 存
        </button>
        <button
          type="primary"
          :disabled="postLoading"
          :loading="postLoading"
          @click="submit"
          class="submit_btn"
        >
          提 交
        </button>
      </view>
    </view>
    <!-- 实际值选择picker -->
    <u-picker
      :show="showPicker"
      :columns="currentColumns"
      :defaultIndex="defaultIndex"
      keyName="text"
      immediateChange
      @cancel="showPicker = false"
      @confirm="changeData"
    ></u-picker>
    <u-modal
      :show="showInfo"
      :content="contentInfo"
      @confirm="showInfo = false"
    ></u-modal>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, computed, watch } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { http } from "@/utils/http";
// import { mockData } from './index';
import UploadImage from "@/components/upload-image-ssr.vue";
import ScanBar from "@/components/scan-bar/index.vue";
import { sizeColorHandle1, sizeColorHandle } from "@/utils/common";
import { useEamStore } from "@/stores/useEamStore";

const props = defineProps({
  id: {
    type: String,
    default: "",
  },
  isRead: {
    type: String,
    default: "0", // 1是查看
  },
});

// 是否折叠
const isCollapse = ref(false);

// 跳转至备件页面
function jumpUrl(url) {
  uni.navigateTo({
    url: url,
    fail: () => {
      uni.showToast({
        title: "敬请期待",
        icon: "error",
      });
    },
  });
}

// 选择设备信息
const deviceList = computed(() => JSON.parse(useEamStore().deviceList));

// 过滤设备信息
function filterDeviceInfo(item) {
  taskInfo.value.parts[partIndex.value] = {
    spareType: item.spareType,
    spareCode: item.spareCode,
    spareName: item.spareNmae,
    spareUnit: item.spareUnit,
    sparePartNumber: "",
    sparePartId: item.id,
  };
}
function addParts() {
  taskInfo.value.parts.push({
    spareType: "",
    spareCode: "",
    spareName: "",
    spareUnit: "",
    sparePartNumber: "",
    sparePartId: "",
  });
}
const partIndex = ref();
function selectPart(index) {
  partIndex.value = index;
  jump("/eam/equ/selectParts/index");
}
// 网页跳转
function jump(item, id = "") {
  uni.navigateTo({
    url: id ? `/pages${item}?id=${id}` : `/pages${item}`,
    fail: () => {
      uni.showToast({
        title: "敬请期待",
        icon: "error",
      });
    },
  });
}
/** 删除行 */
const handleDelete = (index: any) => {
  taskInfo.value.parts.splice(index, 1);
};
// 监控设备选择id
watch(
  () => deviceList,
  async (newVal) => {
    if (newVal.value[0]?.id) {
      filterDeviceInfo(newVal.value[0]);
    }
    setTimeout(() => {
      useEamStore().setDeviceList();
    }, 1000);
  },
  {
    deep: true,
    immediate: true,
  }
);

// 作业方法提示框
const showInfo = ref(false);
const contentInfo = ref("");
function openInfoModal(data) {
  showInfo.value = true;
  contentInfo.value = "";
  if (data.sopItemMethod) {
    contentInfo.value += `作业方法：${data.sopItemMethod}\n\n`;
  }
  if (data.sopItemStandardValue) {
    contentInfo.value += `作业标准：${data.sopItemStandardValue}\n\n`;
  }
  if (data.sopItemTool) {
    contentInfo.value += `作业工具：${data.sopItemTool}\n\n`;
  }
  if (data.sopItemPosition) {
    contentInfo.value += `作业部位：${data.sopItemPosition}\n\n`;
  }
}

onLoad(() => {
  props.id && getDeviceInfo();
});
/**
 * 选择实际值
 */
const showPicker = ref(false);
const currentColumns = reactive([[]]);
const currentIndex = ref();
const defaultIndex = ref([0]);

/**
 * 组织键盘弹出
 */
function hideKeyboard(index, list) {
  const lists = JSON.parse(JSON.stringify(list));
  lists.forEach((item) => {
    item.text = `${item.standardValue} - ${
      item.resultValue == "1" ? "正常" : "异常"
    }`;
  });
  currentIndex.value = index;
  currentColumns[0] = lists ?? [];
  // 给原有的值,赋值picker默认index
  const sopItemValueId = taskInfo.value.details[index].sopItemValueId;
  if (sopItemValueId) {
    const currentIndex = list.findIndex((self) => self.id === sopItemValueId);
    defaultIndex.value = [currentIndex];
  } else {
    defaultIndex.value = [0];
  }
  showPicker.value = true;
  uni.hideKeyboard();
}
function clearData(index) {
  taskInfo.value.details[index].sopItemValueId = "";
  taskInfo.value.details[index].sopItemValue = "";
  showPicker.value = false;
}
function changeData(e) {
  taskInfo.value.details[currentIndex.value].sopItemValue =
    e.value[0].standardValue;
  taskInfo.value.details[currentIndex.value].sopItemValueId = e.value[0].id;
  showPicker.value = false;
}

// 表单详情
let formData = reactive({
  consumeCode: "",
});

// 初始化页面，获取检查详情
let taskInfo = ref<any>({});
const loading = ref(false);

// 表单规则定义
const rules = ref({});

// 摄像头参数设置
const capture = ref(["camera", "album"]);
// 获取图片
function getImages(list, index) {
  const current = JSON.parse(JSON.stringify(taskInfo.value.details))[index];
  current.images = [];
  list?.forEach((item) => {
    current.images.push(item);
  });
  const elder = JSON.parse(JSON.stringify(taskInfo.value.details));
  elder[index] = current;
  taskInfo.value.details = elder;
}

// 获取图片
function getBeforeImages(list, index) {
  const current = JSON.parse(JSON.stringify(taskInfo.value.details))[index];
  current.beforeImages = [];
  list?.forEach((item) => {
    current.beforeImages.push(item);
  });
  const elder = JSON.parse(JSON.stringify(taskInfo.value.details));
  elder[index] = current;
  taskInfo.value.details = elder;
}

// 获取现场图片
function getSceneImages(list) {
  taskInfo.value.images = list;
}
// 获取维修前
function getSceneImages1(list) {
  taskInfo.value.beforeImages = list;
}

// form信息重置
function resetData() {
  taskInfo.value = {};
  formData.consumeCode = "";
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 100,
  });
}

// 重置表单信息 & 光标自动blur
const scanBarRef = ref();
const datekey = ref(new Date());
function resetFields() {
  resetData();
  scanBarRef.value.reset();
  datekey.value = new Date();
}

// 校验提交
const uForm = ref();

// 保存
const saveLoading = ref(false);
async function saveSubmit() {
  console.log(taskInfo.value);
  // 校验是否录入工装编号成功
  if (!taskInfo.value.id) {
    uni.showToast({
      title: "任务id不能为空",
      icon: "none",
    });
    return false;
  }
  // save提交
  saveLoading.value = true;
  const result: any = await http({
    method: "POST",
    url: `/eam/equSelfMaintainOrder/save `,
    data: toRaw(taskInfo.value),
  }).catch(() => {
    saveLoading.value = false;
  });
  if (result?.code == 200) {
    uni.showToast({
      title: "保存成功",
    });
    // uni.navigateBack();
  }
  saveLoading.value = false;
}

// 提交
const postLoading = ref(false);
async function submit() {
  console.log(taskInfo.value);
  // 校验是否录入工装编号成功
  if (!taskInfo.value.id) {
    uni.showToast({
      title: "任务id不能为空",
      icon: "none",
    });
    return false;
  }
  // 校验必填项是否填写
  const infos = taskInfo.value?.details ?? [];
  if (infos.length) {
    for (let i = 0; i < infos.length; i++) {
      if (infos[i].sopItem.sopExecute == "1" && !infos[i].sopItemValue) {
        uni.showToast({
          title: `${infos[i].sopItemName}的实际值不能为空`,
          icon: "none",
        });
        return false;
      }
    }
  }
  // save提交
  postLoading.value = true;
  const result: any = await http({
    method: "POST",
    url: `/eam/equSelfMaintainOrder/submit`,
    data: toRaw(taskInfo.value),
  }).catch(() => {
    postLoading.value = false;
  });
  if (result?.code == 200) {
    uni.showToast({
      title: "提交成功",
    });
    uni.navigateBack();
  }
  postLoading.value = false;
}

// 获取工装信息（接口请求）
async function getDeviceInfo() {
  loading.value = true;
  const data: any = await http({
    method: "GET",
    url: `/eam/equSelfMaintainOrder/get/${props.id}`,
    data: {},
  }).catch(() => {
    loading.value = false;
  });
  if (data?.data) {
    taskInfo.value = {
      ...data?.data,
      parts: data?.data?.parts || [],
    };
  }
  console.log("data", data);
  loading.value = false;
  // 模拟数据返回，调试使用（保留）
  // setTimeout(() => {
  // 	loading.value = false;
  // 	taskInfo.value = JSON.parse(JSON.stringify(mockData));
  // }, 500);
}
</script>

<style lang="scss" scoped>
@import "@/static/css/standard_item.scss";

:deep(.u-modal__content__text) {
  font-size: 14px;
}

:deep(.u-modal__content) {
  padding: 15px 15px 0;
}
</style>
